package com.company.test20;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Created by Administrator on 2016.9.26.
 */
public class Test2019 extends JFrame {
    private Draw draw;
    private Control control;

    public Test2019(){
        draw=new Draw();
        control=new Control();
        add(draw,BorderLayout.CENTER);
        add(control,BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        JFrame frame=new Test2019();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("递归");
        frame.setSize(400,400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    class Draw extends JPanel{
        private int time;
        public Draw(){
            time=0;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Point p1=new Point(300,10);
            Point p2=new Point(10,600);
            Point p3=new Point(600,600);

            g.drawLine(p1.x,p1.y,p2.x,p2.y);
            g.drawLine(p1.x,p1.y,p3.x,p3.y);
            g.drawLine(p2.x,p2.y,p3.x,p3.y);

            paint(g,time,p1,p2,p3);
        }

        public void paint(Graphics g,int time,Point p1, Point p2,Point p3){
            if(time<=0){
                return;
            }

            g.drawLine(center(p1,p2).x,center(p1,p2).y,center(p1,p3).x,center(p1,p3).y);
            g.drawLine(center(p1,p3).x,center(p1,p3).y,center(p2,p3).x,center(p2,p3).y);
            g.drawLine(center(p1,p2).x,center(p1,p2).y,center(p2,p3).x,center(p2,p3).y);

            paint(g,time-1,p1,center(p1,p2),center(p1,p3));
            paint(g,time-1,p2,center(p2,p1),center(p2,p3));
            paint(g,time-1,p3,center(p3,p1),center(p3,p2));
        }

        public Point center(Point p1,Point p2){
            Point point=new Point();
            point.x=(p1.x+p2.x)/2;
            point.y=(p1.y+p2.y)/2;
            return point;
        }
    }

    class Control extends JPanel{
        private JButton letf;
        private JButton right;

        public Control(){
            letf=new JButton("<");
            right=new JButton(">");

            letf.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    super.mousePressed(e);
                    Test2019.this.draw.time--;
                    Test2019.this.draw.repaint();
                }
            });

            right.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    super.mousePressed(e);
                    Test2019.this.draw.time++;
                    Test2019.this.draw.repaint();
                }
            });
            this.add(letf);
            this.add(right);
        }
    }
}